<template>
  <a-modal
    v-model:open="open"
    title="AI智能分组"
    @ok="handleOk"
    :width="1100"
    :maskClosable="false"
    class="ai-modal"
    :bodyStyle="{ maxHeight: '500px', overflow: 'auto' }"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="{ style: { width: '75px' } }"
      :disabled="modelType == 'seeInfo'"
    >
      <a-form-item label="分组名称" name="groupName">
        <a-input v-model:value="formState.groupName" allowClear autocomplete="off"></a-input>
      </a-form-item>
      <a-form-item label="备注信息" name="remark">
        <a-input v-model:value="formState.remark" allowClear></a-input>
      </a-form-item>
    </a-form>
    <div class="title-item"><sup style="color: red">*</sup> 入组条件编辑</div>
    <div>
      <div v-for="(item, index) in eventList" :key="index">
        {{ item.title }}
        &nbsp; 发生时间&nbsp;
        <a-input-number
          :min="1"
          :step="1"
          :precision="0"
          :disabled="modelType == 'seeInfo' || item.timeSuffix == '无限制'"
          v-model:value="item.startTime"
          :style="{ width: '80px' }"
        ></a-input-number>
        <span style="margin: 0 3px">至</span>
        <a-input-number
          :min="1"
          :step="1"
          :precision="0"
          :disabled="modelType == 'seeInfo' || item.timeSuffix != '之间'"
          v-model:value="item.endTime"
          :style="{ width: '80px' }"
        ></a-input-number>
        &nbsp;
        <a-radio-group v-model:value="item.unit" :disabled="modelType == 'seeInfo'">
          <a-radio value="年">年</a-radio>
          <a-radio value="月">月</a-radio>
          <a-radio value="日">日</a-radio>
        </a-radio-group>
        <a-select
          v-model:value="item.timeSuffix"
          style="width: 100px"
          :disabled="modelType == 'seeInfo'"
          @change="changeTimeSuffix($event, item)"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        >
          <a-select-option label="之前" value="之前"></a-select-option>
          <a-select-option label="之内" value="之内"></a-select-option>
          <a-select-option label="之间" value="之间"></a-select-option>
          <a-select-option label="之时" value="之时"></a-select-option>
          <a-select-option label="无限制" value="无限制"></a-select-option>
        </a-select>
        &nbsp;事件名称&nbsp;
        <a-select
          v-model:value="item.eventType"
          style="width: 70px"
          @change="eventTypeChange($event, item)"
          :disabled="modelType == 'seeInfo'"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        >
          <a-select-option value="诊断">诊断</a-select-option>
          <a-select-option value="手术">手术</a-select-option>
          <a-select-option value="药品">药品</a-select-option>
          <a-select-option value="检验">检验</a-select-option>
          <a-select-option value="检查">检查</a-select-option>
          <a-select-option value="年龄">年龄</a-select-option>
          <a-select-option value="性别">性别</a-select-option>
        </a-select>
        &nbsp;
        <template v-if="item.eventType == '年龄'">
          <a-select
            style="width: 70px"
            v-model:value="item.compare"
            :disabled="modelType == 'seeInfo'"
            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          >
            <a-select-option label="=" value="="></a-select-option>
            <a-select-option label=">" value=">"></a-select-option>
            <a-select-option label="≥" value="≥"></a-select-option>
            <a-select-option label="<" value="<"></a-select-option>
            <a-select-option label="≤" value="≤"></a-select-option>
            <a-select-option label="≠" value="≠"></a-select-option>
          </a-select>
          &nbsp;
          <a-input
            :disabled="modelType == 'seeInfo'"
            v-model:value="item.event"
            placeholder="请输入结果描述"
            :style="{ width: '215px' }"
            allowClear
          ></a-input>
        </template>
        <a-auto-complete
          v-else
          v-model:value="item.event"
          :options="item.dictData"
          :style="{ width: '295px' }"
          :disabled="modelType == 'seeInfo'"
          placeholder="请输入事件名称"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          :filterOption="
            (inputValue, option) =>
              option.value.toUpperCase().indexOf(item.event.toUpperCase()) >= 0
          "
        >
        </a-auto-complete>
        <!-- <a-input
          v-else
          :disabled="modelType == 'seeInfo'"
          v-model:value="item.event"
          placeholder="请输入事件名称"
          :style="{ width: '295px' }"
          allowClear
        ></a-input> -->
        &nbsp;
        <icon-font
          v-if="modelType != 'seeInfo'"
          style="color: red; font-size: 16px"
          class="icon-del"
          type="icon-shanchu"
          @click="removeEvent(index)"
        />
        <!-- <span style="cursor: pointer" @click="removeEvent(index)" v-if="modelType != 'seeInfo'">
          <MinusCircleOutlined style="color: red" />
        </span> -->
        <template v-if="item.eventType == '检验' || item.eventType == '检查'">
          <br />
          <div style="text-align: right; padding-right: 30px; margin-top: 5px">
            <span>结果</span>&nbsp;
            <a-select
              style="width: 70px"
              v-model:value="item.compare"
              :disabled="modelType == 'seeInfo'"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            >
              <a-select-option label="=" value="="></a-select-option>
              <a-select-option label=">" value=">"></a-select-option>
              <a-select-option label="≥" value="≥"></a-select-option>
              <a-select-option label="<" value="<"></a-select-option>
              <a-select-option label="≤" value="≤"></a-select-option>
              <a-select-option label="≠" value="≠"></a-select-option>
            </a-select>
            &nbsp;
            <a-input
              :disabled="modelType == 'seeInfo'"
              v-model:value="item.result"
              placeholder="请输入结果描述"
              style="width: 295px"
              allowClear
            ></a-input>
          </div>
        </template>
        <a-divider v-if="index != eventList.length - 1" style="margin: 10px 0" />
      </div>
    </div>
    <a-divider style="margin: 18px 0" />
    <div class="title-item-tip" v-if="checkBtnList.length > 6">
      逻辑式
      <icon-font
        v-if="modelType != 'seeInfo'"
        style="color: red; font-size: 16px; float: right; padding: 0 1px"
        class="icon-del"
        type="icon-shanchu"
        @click="removeExpressionBtn"
      />
      <!-- <span
        @click="removeExpressionBtn"
        style="float: right; padding: 0 5px; cursor: pointer"
        v-if="modelType != 'seeInfo'"
      >
        <MinusCircleOutlined style="color: red" />
      </span> -->
    </div>
    <div v-if="checkBtnList.length > 6">
      <div style="line-height: 40px" class="check-tags">
        <span class="item-name">可选按钮</span>
        <a-tag
          color="#e8f7ff"
          v-for="(item, index) in checkBtnList"
          :key="index"
          @click="tagEventBtn(item)"
        >
          {{ item }}
        </a-tag>
      </div>
      <div style="line-height: 40px; display: flex; flex-direction: row">
        <span class="item-name">编辑逻辑式</span>
        <div style="width: 100%; border: 1px solid #e5e6eb; padding: 0 10px; border-radius: 2px">
          <a-tag
            @close="handleCloseExpression(item, index)"
            v-for="(item, index) in expressionData"
            :key="item.tm"
            :bordered="false"
            color="processing"
            :closable="modelType != 'seeInfo'"
            >{{ item.value }}</a-tag
          >
        </div>
      </div>
    </div>
    <div style="margin-top: 10px" v-if="modelType != 'seeInfo'">
      <a-row :gutter="10">
        <a-col :span="12">
          <a-button
            style="width: 100%; color: #165dff; border-color: #165dff"
            :icon="h(PlusOutlined)"
            @click="addEventBtn"
          >
            新增事件
          </a-button>
        </a-col>
        <a-col :span="12">
          <a-button
            style="width: 100%"
            :style="{
              borderColor: checkBtnList.length ? '#d9d9d9' : '#165DFF',
              color: checkBtnList.length ? '#00000040' : '#165DFF'
            }"
            :disabled="checkBtnList.length ? true : false"
            :icon="h(PlusOutlined)"
            @click="addExpressionBtn"
          >
            新增逻辑式
          </a-button>
        </a-col>
      </a-row>
    </div>
    <div class="title-item">&nbsp;&nbsp;排除条件编辑</div>
    <div>
      <div v-for="(item, index) in excludeConditionList" :key="index">
        {{ item.title }}
        &nbsp; 发生时间&nbsp;
        <a-input-number
          :min="1"
          :step="1"
          :precision="0"
          :disabled="modelType == 'seeInfo' || item.timeSuffix == '无限制'"
          v-model:value="item.startTime"
          :style="{ width: '80px' }"
        ></a-input-number>
        <span style="margin: 0 3px">至</span>
        <a-input-number
          :min="1"
          :step="1"
          :precision="0"
          :disabled="modelType == 'seeInfo' || item.timeSuffix != '之间'"
          v-model:value="item.endTime"
          :style="{ width: '80px' }"
        ></a-input-number>
        &nbsp;
        <a-radio-group v-model:value="item.unit" :disabled="modelType == 'seeInfo'">
          <a-radio value="年">年</a-radio>
          <a-radio value="月">月</a-radio>
          <a-radio value="日">日</a-radio>
        </a-radio-group>
        <a-select
          v-model:value="item.timeSuffix"
          style="width: 100px"
          :disabled="modelType == 'seeInfo'"
          @change="changeTimeSuffix($event, item)"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        >
          <a-select-option label="之前" value="之前"></a-select-option>
          <a-select-option label="之内" value="之内"></a-select-option>
          <a-select-option label="之间" value="之间"></a-select-option>
          <a-select-option label="之时" value="之时"></a-select-option>
          <a-select-option label="无限制" value="无限制"></a-select-option>
        </a-select>
        &nbsp;事件名称&nbsp;
        <a-select
          v-model:value="item.eventType"
          style="width: 70px"
          @change="eventTypeChange($event, item)"
          :disabled="modelType == 'seeInfo'"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        >
          <a-select-option value="诊断">诊断</a-select-option>
          <a-select-option value="手术">手术</a-select-option>
          <a-select-option value="药品">药品</a-select-option>
          <a-select-option value="检验">检验</a-select-option>
          <a-select-option value="检查">检查</a-select-option>
          <a-select-option value="年龄">年龄</a-select-option>
          <a-select-option value="性别">性别</a-select-option>
        </a-select>
        &nbsp;
        <template v-if="item.eventType == '年龄'">
          <a-select
            style="width: 70px"
            v-model:value="item.compare"
            :disabled="modelType == 'seeInfo'"
            :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          >
            <a-select-option label="=" value="="></a-select-option>
            <a-select-option label=">" value=">"></a-select-option>
            <a-select-option label="≥" value="≥"></a-select-option>
            <a-select-option label="<" value="<"></a-select-option>
            <a-select-option label="≤" value="≤"></a-select-option>
            <a-select-option label="≠" value="≠"></a-select-option>
          </a-select>
          &nbsp;
          <a-input
            :disabled="modelType == 'seeInfo'"
            v-model:value="item.event"
            placeholder="请输入结果描述"
            :style="{ width: '215px' }"
            allowClear
          ></a-input>
        </template>

        <a-auto-complete
          v-else
          v-model:value="item.event"
          :options="item.dictData"
          :style="{ width: '295px' }"
          :disabled="modelType == 'seeInfo'"
          placeholder="请输入事件名称"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          :filterOption="
            (inputValue, option) =>
              option.value.toUpperCase().indexOf(item.event.toUpperCase()) >= 0
          "
        >
        </a-auto-complete>
        <!-- <a-input v-else :disabled="modelType == 'seeInfo'" v-model:value="item.event" placeholder="请输入事件名称"
          :style="{ width: '295px' }" allowClear></a-input> -->
        &nbsp;
        <icon-font
          v-if="modelType != 'seeInfo'"
          style="color: red; font-size: 16px"
          class="icon-del"
          type="icon-shanchu"
          @click="removeExcludeEvent(index)"
        />
        <!-- <span
          style="cursor: pointer"
          @click="removeExcludeEvent(index)"
          v-if="modelType != 'seeInfo'"
        >
          <MinusCircleOutlined style="color: red" />
        </span> -->
        <template v-if="item.eventType == '检验' || item.eventType == '检查'">
          <br />
          <div style="text-align: right; padding-right: 30px; margin-top: 5px">
            <span>结果</span>&nbsp;
            <a-select
              style="width: 70px"
              v-model:value="item.compare"
              :disabled="modelType == 'seeInfo'"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            >
              <a-select-option label="=" value="="></a-select-option>
              <a-select-option label=">" value=">"></a-select-option>
              <a-select-option label="≥" value="≥"></a-select-option>
              <a-select-option label="<" value="<"></a-select-option>
              <a-select-option label="≤" value="≤"></a-select-option>
              <a-select-option label="≠" value="≠"></a-select-option>
            </a-select>
            &nbsp;
            <a-input
              :disabled="modelType == 'seeInfo'"
              v-model:value="item.result"
              placeholder="请输入结果描述"
              style="width: 295px"
              allowClear
            ></a-input>
          </div>
        </template>
        <a-divider v-if="index != excludeConditionList.length - 1" style="margin: 10px 0" />
      </div>
    </div>
    <a-divider style="margin: 18px 0" />
    <div class="title-item-tip" v-if="checkExcludeBtnList.length > 6">
      逻辑式
      <icon-font
        v-if="modelType != 'seeInfo'"
        style="color: red; font-size: 16px; float: right; padding: 0 1px"
        class="icon-del"
        type="icon-shanchu"
        @click="removeExcludeExpressionBtn"
      />
      <!-- <span
        @click="removeExcludeExpressionBtn"
        style="float: right; padding: 0 5px; cursor: pointer"
        v-if="modelType != 'seeInfo'"
      >
        <MinusCircleOutlined style="color: red" />
      </span> -->
    </div>
    <div v-if="checkExcludeBtnList.length > 6">
      <div style="line-height: 40px" class="check-tags">
        <span class="item-name">可选按钮</span>
        <a-tag
          color="#e8f7ff"
          v-for="(item, index) in checkExcludeBtnList"
          :key="index"
          @click="tagExcludeEventBtn(item)"
        >
          {{ item }}
        </a-tag>
      </div>
      <div style="line-height: 40px; display: flex; flex-direction: row">
        <span class="item-name">编辑逻辑式</span>
        <div style="width: 100%; border: 1px solid #e5e6eb; padding: 0 10px; border-radius: 2px">
          <a-tag
            @close="handleCloseExclude(item, index)"
            :closable="modelType != 'seeInfo'"
            v-for="(item, index) in excludeExpressionData"
            :key="item.tm"
            :bordered="false"
            color="processing"
            >{{ item.value }}</a-tag
          >
        </div>
      </div>
    </div>
    <div style="margin-top: 10px" v-if="modelType != 'seeInfo'">
      <a-row :gutter="10">
        <a-col :span="12">
          <a-button
            :style="{ borderColor: '#165DFF' }"
            style="width: 100%; color: #165dff"
            :icon="h(PlusOutlined)"
            @click="addExcludeEventBtn"
          >
            新增事件
          </a-button>
        </a-col>
        <a-col :span="12">
          <a-button
            style="width: 100%; color: #165dff"
            :style="{
              borderColor: checkExcludeBtnList.length ? '#d9d9d9' : '#165DFF',
              color: checkExcludeBtnList.length ? '#00000040' : '#165DFF'
            }"
            :disabled="checkExcludeBtnList.length ? true : false"
            :icon="h(PlusOutlined)"
            @click="addExcludeExpressionBtn"
          >
            新增逻辑式
          </a-button>
        </a-col>
      </a-row>
    </div>
    <div class="title-item">&nbsp;&nbsp;诊疗阶段编辑</div>
    <div>
      <div v-for="(item, index) in treatStageData" :key="index">
        阶段{{ index + 1 }} &nbsp; 阶段名称 &nbsp;
        <a-input
          v-model:value="item.name"
          placeholder="请输入阶段名称"
          style="width: 290px"
          allowClear
          :disabled="modelType == 'seeInfo'"
        />
        &nbsp;划分依据&nbsp;
        <a-select
          v-model:value="item.eventType"
          style="width: 100px"
          @change="eventTypeChange($event, item)"
          :disabled="modelType == 'seeInfo'"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
        >
          <a-select-option value="诊断">诊断</a-select-option>
          <a-select-option value="手术">手术</a-select-option>
          <a-select-option value="药品">药品</a-select-option>
          <a-select-option value="检验">检验</a-select-option>
          <a-select-option value="检查">检查</a-select-option>
          <a-select-option value="用药提醒">用药提醒</a-select-option>
          <a-select-option value="复查提醒">复查提醒</a-select-option>
        </a-select>
        &nbsp;
        <a-auto-complete
          v-model:value="item.event"
          :options="item.dictData"
          :style="{ width: '426px' }"
          :disabled="modelType == 'seeInfo'"
          placeholder="请输入事件名称"
          :getPopupContainer="(triggerNode) => triggerNode.parentNode"
          :filterOption="
            (inputValue, option) =>
              option.value.toUpperCase().indexOf(item.event.toUpperCase()) >= 0
          "
        >
        </a-auto-complete>
        <!-- <a-input :disabled="modelType == 'seeInfo'" v-model:value="item.event" placeholder="请输入事件名称" style="width: 428px"
          allowClear></a-input> -->
        &nbsp;
        <icon-font
          v-if="modelType != 'seeInfo'"
          style="color: red; font-size: 16px"
          class="icon-del"
          type="icon-shanchu"
          @click="removeTreatStageEvent(index)"
        />
        <!-- <span
          style="cursor: pointer"
          @click="removeTreatStageEvent(index)"
          v-if="modelType != 'seeInfo'"
        >
          <MinusCircleOutlined style="color: red" />
        </span> -->
        <template v-if="item.eventType == '检验' || item.eventType == '检查'">
          <br />
          <div style="text-align: right; padding-right: 29px; margin-top: 5px">
            <span>结果</span>&nbsp;
            <a-select
              style="width: 100px"
              v-model:value="item.compare"
              :disabled="modelType == 'seeInfo'"
              :getPopupContainer="(triggerNode) => triggerNode.parentNode"
            >
              <a-select-option label="=" value="="></a-select-option>
              <a-select-option label=">" value=">"></a-select-option>
              <a-select-option label="≥" value="≥"></a-select-option>
              <a-select-option label="<" value="<"></a-select-option>
              <a-select-option label="≤" value="≤"></a-select-option>
              <a-select-option label="≠" value="≠"></a-select-option>
            </a-select>
            &nbsp;
            <a-input
              :disabled="modelType == 'seeInfo'"
              v-model:value="item.result"
              placeholder="请输入结果描述"
              style="width: 426px"
              allowClear
            ></a-input>
          </div>
        </template>
        <a-divider v-if="index != treatStageData.length - 1" style="margin: 10px 0" />
      </div>
    </div>
    <div style="margin-top: 10px" v-if="modelType != 'seeInfo'">
      <a-button
        :style="{ borderColor: '#165DFF' }"
        style="width: 100%; color: #165dff"
        :icon="h(PlusOutlined)"
        @click="addTreatStageBtn"
      >
        新增阶段
      </a-button>
    </div>
    <template #footer>
      <a-button key="back" @click="open = false">取消</a-button>
      <a-button v-if="modelType != 'seeInfo'" type="primary" :loading="btnLoading" @click="handleOk"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
import { reactive, ref, toRaw, onMounted, h } from 'vue'
import type { UnwrapRef } from 'vue'
import type { Rule } from 'ant-design-vue/es/form'
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons-vue'
import { getListByName, saveAiGroup, getEventName } from '@/api/patientManagement/ai-group.ts'
import { message } from 'ant-design-vue'
import store from '@/store'
import { dataTool } from 'echarts'
import type { AnymatchFn } from 'vite'
const emit = defineEmits(['close'])

const modelMaxHeight = ref(window.innerHeight * 0.8 - 150 + 'px')

interface FormState {}

const modelType = ref('')

const formRef = ref()
const btnLoading = ref(false)

const formState: UnwrapRef<FormState> = reactive({
  groupName: '',
  remark: ''
})

const rules: Record<string, Rule[]> = {
  groupName: [{ required: true, trigger: 'blur' }]
}

const open = ref<boolean>(false)

const checkList = ['(', ')', 'and', 'or', 'not']
const checkBtnList = ref([]) // 入组
const checkExcludeBtnList = ref([]) // 排除

// 事件
const eventList = ref([])
const excludeConditionList = ref([])
// 逻辑式
const expressionData = ref([])
const excludeExpressionData = ref([]) // 排除

// 阶段
const treatStageData = ref([])

const init = (type, groupId) => {
  modelType.value = type
  open.value = true
  btnLoading.value = false

  checkBtnList.value = []
  checkExcludeBtnList.value = []
  eventList.value = []
  excludeConditionList.value = []
  expressionData.value = []
  excludeExpressionData.value = []
  treatStageData.value = []

  formState.id = ''

  if (formRef.value) {
    formRef.value.resetFields()
  }

  if (type == 'seeInfo') {
    getGroupInfo(groupId)
  }
}

// const nameSelect = (value, data) =>{
//   console.log(value, data)
// }

const getGroupInfo = (id) => {
  getListByName(id).then((res) => {
    if (res.data) {
      Object.assign(formState, res.data)
    }

    let excludeCondition = {}
    if (formState.excludeCondition) {
      try {
        excludeCondition = JSON.parse(formState.excludeCondition) // 排除
        if (typeof excludeCondition == 'object') {
        } else {
          return false
        }
      } catch {
        return false
      }
    }

    let includeCondition = {}
    if (formState.includeCondition) {
      try {
        includeCondition = JSON.parse(formState.includeCondition) // 入组
        if (typeof includeCondition == 'object') {
        } else {
          return false
        }
      } catch {
        return false
      }
    }

    // 入组
    if (includeCondition) {
      includeCondition.condition.forEach((element) => {
        element.dateTime = [
          element.startTime ? dayjs(element.startTime) : '',
          element.endTime ? dayjs(element.endTime) : ''
        ]
      })
      eventList.value = includeCondition.condition
      addExpressionBtn()

      // 逻辑式
      const expression = includeCondition.expression
      const expressionList = expression.split(' ')
      for (let i = 0; i < expressionList.length; i++) {
        if (expressionList[i]) {
          expressionData.value.push({
            tm: new Date().getTime(),
            value: expressionList[i]
          })
        }
      }
    }
    // 排除
    if (excludeCondition) {
      excludeCondition.condition.forEach((element) => {
        element.dateTime = [
          element.startTime ? dayjs(element.startTime) : '',
          element.endTime ? dayjs(element.endTime) : ''
        ]
      })
      excludeConditionList.value = excludeCondition.condition
      addExcludeExpressionBtn()

      // 逻辑式
      const expression = excludeCondition.expression
      const expressionList = expression.split(' ')
      for (let i = 0; i < expressionList.length; i++) {
        if (expressionList[i]) {
          excludeExpressionData.value.push({
            tm: new Date().getTime(),
            value: expressionList[i]
          })
        }
      }
    }

    let treatStage = {}
    if (formState.treatStage) {
      try {
        treatStage = JSON.parse(formState.treatStage) // 诊疗
        if (typeof treatStage == 'object') {
        } else {
          return false
        }
      } catch {
        return false
      }
    }

    if (treatStage) {
      treatStageData.value = treatStage
    }
  })
}

const handleCloseExpression = (removetag, index) => {
  expressionData.value = expressionData.value.slice(0, index)
  // expressionData.value.splice(index, 1)
}

const handleCloseExclude = (removeTag, index) => {
  // const tags = excludeExpressionData.value.filter((tag) => tag !== removeTag)
  excludeExpressionData.value = excludeExpressionData.value.slice(0, index)
  // excludeExpressionData.value.splice(index, 1)
  // nextTick(() => {

  //   excludeExpressionData.value = JSON.parse(JSON.stringify(excludeExpressionData.value))
  // })
}

const changeTimeSuffix = (e, data) => {
  if (e == '无限制') {
    data.startTime = ''
    data.endTime = ''
  }
  if (e != '之间') {
    data.endTime = ''
  }
}

const handleOk = () => {
  formRef.value
    .validate()
    .then(() => {
      // 入组
      let includeCondition = {
        condition: [],
        expression: expressionAttrToString(expressionData.value)
      }

      if (eventList.value.length == 0) {
        message.error('请添加事件')
        return
      } else {
        const eventNoDataList = eventList.value.filter((ele) => !ele.event)
        if (eventNoDataList.length) {
          message.error('请输入入组条件的事件名称')
          return
        }

        // 时间判断
        const timeData = eventList.value.filter((ele) => ele.timeSuffix == '之间')
        if (timeData.length > 0) {
          const timeDataList = timeData.filter(
            (ele) => (ele.startTime && !ele.endTime) || (!ele.startTime && ele.endTime)
          )
          if (timeDataList.length > 0) {
            message.error('请输入入组条件的时间')
            return
          }
        }

        const eventNoResultData = eventList.value.filter((ele) => {
          if (ele.eventType == '检查' || ele.eventType == '检验') {
            if (!ele.result) return ele
          }
        })
        if (eventNoResultData.length) {
          message.error('请输入入组条件的结果描述')
          return
        }

        eventList.value.forEach((item) => {
          const conditionItem = {
            endTime: item.endTime,
            event: item.event,
            eventType: item.eventType,
            result: item.eventType == '年龄' ? item.event : item.result,
            startTime: item.startTime,
            timeSuffix: item.timeSuffix,
            title: item.title,
            unit: item.unit,
            compare: item.compare
          }
          includeCondition.condition.push(conditionItem)
        })
      }

      if (includeCondition.condition.length > 1) {
        if (!checkBtnList.value.length) {
          message.error('请编辑入组条件编辑逻辑式')
          return
        }
        if (!expressionData.value.length) {
          message.error('请编辑入组条件编辑逻辑式')
          return
        }
      }

      includeCondition.expression = includeCondition.condition.length
        ? expressionAttrToString(expressionData.value)
        : ''

      // 排除

      let excludeCondition = {
        condition: [],
        expression: expressionAttrToString(excludeExpressionData.value)
      }

      if (excludeConditionList.value.length) {
        const eventNoDataList = excludeConditionList.value.filter((ele) => !ele.event)
        if (eventNoDataList.length) {
          message.error('请输入排除条件的事件名称')
          return
        }

        // 时间判断
        const excludetimeData = excludeConditionList.value.filter((ele) => ele.timeSuffix == '之间')
        if (excludetimeData.length > 0) {
          const excludetimeDataList = excludetimeData.filter(
            (ele) => (ele.startTime && !ele.endTime) || (!ele.startTime && ele.endTime)
          )
          if (excludetimeDataList.length > 0) {
            message.error('请输入排除条件的时间')
            return
          }
        }

        const eventNoResultData = excludeConditionList.value.filter((ele) => {
          if (ele.eventType == '检查' || ele.eventType == '检验') {
            if (!ele.result) return ele
          }
        })
        if (eventNoResultData.length) {
          message.error('请输入排除条件的结果描述')
          return
        }

        excludeConditionList.value.forEach((item) => {
          const conditionItem = {
            endTime: item.endTime,
            event: item.event,
            eventType: item.eventType,
            result: item.eventType == '年龄' ? item.event : item.result,
            startTime: item.startTime,
            timeSuffix: item.timeSuffix,
            title: item.title,
            unit: item.unit,
            compare: item.compare
          }
          excludeCondition.condition.push(conditionItem)
        })

        if (excludeCondition.condition.length > 1) {
          if (!excludeExpressionData.value.length) {
            message.error('请编辑排除条件编辑逻辑式')
            return
          }
        }
      }

      excludeCondition.expression = excludeCondition.condition.length
        ? expressionAttrToString(excludeExpressionData.value)
        : ''

      if (treatStageData.value.length) {
        if (treatStageData.value.length == 1) {
          if (!treatStageData.value[0].name) {
            message.error('诊疗阶段名称未填写')
            return
          }
          if (!treatStageData.value[0].event) {
            message.error('诊疗阶段事件名称未填写')
            return
          }
          if (
            treatStageData.value[0].eventType == '检查' ||
            treatStageData.value[0].eventType == '检验'
          ) {
            if (!treatStageData.value[0].result) {
              message.error('请输入诊疗阶段的结果描述')
              return
            }
          }
        } else {
          if (treatStageData.value[treatStageData.value.length - 1].event) {
            const treatStageNoEventData = treatStageData.value.filter(
              (item, index) => !item.event && index != treatStageData.value.length - 1
            )
            if (treatStageNoEventData.length) {
              message.error('诊疗阶段事件名称未填写')
              return
            }

            const eventNoResultData = treatStageData.value.filter((ele) => {
              if (ele.eventType == '检查' || ele.eventType == '检验') {
                if (!ele.result) return ele
              }
            })
            if (eventNoResultData.length) {
              message.error('请输入诊疗阶段的结果描述')
              return
            }
          } else {
            const treatStageNoEventData = treatStageData.value.filter(
              (item, index) => !item.event && index != treatStageData.value.length - 1
            )
            if (treatStageNoEventData.length) {
              message.error('诊疗阶段事件名称未填写')
              return
            }

            const eventNoResultData = treatStageData.value.filter((ele) => {
              if (ele.eventType == '检查' || ele.eventType == '检验') {
                if (!ele.result) return ele
              }
            })
            if (eventNoResultData.length) {
              message.error('请输入诊疗阶段的结果描述')
              return
            }

            treatStageData.value.splice(treatStageData.value.length - 1, 1)
          }
        }

        treatStageData.value.forEach((item) => {
          delete item.dictData
        })
      }

      btnLoading.value = true
      const data = {
        id: formState.id ? formState.id : '',
        groupName: formState.groupName,
        userId: store.userApp.userInfo.id,
        remark: formState.remark,
        creator: store.userApp.userInfo.id,
        includeCondition: JSON.stringify(includeCondition), // 入组
        excludeCondition: JSON.stringify(excludeCondition), // 排除
        treatStage: JSON.stringify(treatStageData.value) // 诊疗
      }

      saveAiGroup(data).then(() => {
        message.success('新增成功')
        open.value = false
        btnLoading.value = false
        emit('close')
      })
    })
    .catch(() => {
      btnLoading.value = false
    })
}

// 逻辑式attr to string
const expressionAttrToString = (data) => {
  let string = ''
  data.forEach((item, index) => {
    if (index) {
      string = string + ' ' + item.value
    } else {
      string = item.value
    }
  })
  return string
}

// 时间数据转换为时间字符串
const timeDataToTimeString = (data, dateType) => {
  let string = ''

  switch (dateType) {
    case '年':
      string = dayjs(data).format('YYYY')
      break
    case '月':
      string = dayjs(data).format('YYYY-MM')
      break
    case '日':
      string = dayjs(data).format('YYYY-MM-DD')
      break
  }
  return string
}

const unitChangeDateType = (name) => {
  let dateType = ''
  switch (name) {
    case '年':
      dateType = 'year'
      break
    case '月':
      dateType = 'month'
      break
    case '日':
      dateType = 'day'
      break
  }
  return dateType
}

// 排除
const unitExcludeChangeDateType = (name) => {
  let dateType = ''
  switch (name) {
    case '年':
      dateType = 'year'
      break
    case '月':
      dateType = 'month'
      break
    case '日':
      dateType = 'day'
      break
  }
  return dateType
}

const filterOption = (input: string, option: Option) => {
  return option.value.toUpperCase().indexOf(input.toUpperCase()) >= 0
}

// 入组
const addEventBtn = async () => {
  let data = []
  await getEventName({ dictTypeId: 1 }).then((res) => {
    data = res.data
  })
  eventList.value.push({
    title: '事件' + (Number(eventList.value.length) + 1),
    dateTime: [],
    startTime: '',
    endTime: '',
    unit: '年',
    timeSuffix: '无限制',
    eventType: '诊断',
    event: '',
    result: '',
    compare: '=',
    dictData: data
  })

  if (checkBtnList.value.length) {
    addExpressionBtn()
  }
}

// 排除
const addExcludeEventBtn = async () => {
  let data = []
  await getEventName({ dictTypeId: 1 }).then((res) => {
    data = res.data
  })
  excludeConditionList.value.push({
    title: '事件' + (Number(excludeConditionList.value.length) + 1),
    dateTime: [],
    startTime: '',
    endTime: '',
    unit: '年',
    timeSuffix: '无限制',
    eventType: '诊断',
    event: '',
    result: '',
    compare: '=',
    dictData: data
  })

  if (checkExcludeBtnList.value.length) {
    addExcludeExpressionBtn()
  }
}

const eventTypeChange = async (value, data) => {
  data.eventType = value

  data.event = ''
  data.result = ''
  data.dictData = []

  let eventId: any = ''
  switch (value) {
    case '诊断':
      eventId = 1
      break
    case '药品':
      eventId = 2
      break
    case '手术':
      eventId = 3
      break
    case '检验':
      eventId = 4
      break
    case '检查':
      eventId = 5
      break
    default:
      eventId = 0
      break
  }

  if (eventId) {
    await getEventName({ dictTypeId: eventId }).then((res) => {
      data.dictData = res.data
    })
  }
}

const removeEvent = (index) => {
  eventList.value.splice(index, 1)
  eventList.value.forEach((item, index: number) => {
    item.title = '事件' + (index + 1)
  })
  if (checkBtnList.value.length) {
    addExpressionBtn()
  }

  expressionData.value = []
}

const removeExcludeEvent = (index) => {
  excludeConditionList.value.splice(index, 1)
  excludeConditionList.value.forEach((item, index: number) => {
    item.title = '事件' + (index + 1)
  })
  if (checkExcludeBtnList.value.length) {
    addExcludeExpressionBtn()
  }

  excludeExpressionData.value = []
}

const removeTreatStageEvent = (index) => {
  treatStageData.value.splice(index, 1)
  treatStageData.value.forEach((item, index: number) => {
    item.title = '阶段' + (index + 1)
  })
}

// 入组
const addExpressionBtn = () => {
  const checkVailData = []
  eventList.value.forEach((item: any, index: number) => {
    checkVailData.push(item.title)
  })
  checkBtnList.value = [...checkList, ...checkVailData]
}

// 排除
const addExcludeExpressionBtn = () => {
  const checkVailData = []
  excludeConditionList.value.forEach((item: any, index: number) => {
    checkVailData.push(item.title)
  })
  checkExcludeBtnList.value = [...checkList, ...checkVailData]
}

const removeExpressionBtn = () => {
  expressionData.value = []
  checkBtnList.value = []
}

const removeExcludeExpressionBtn = () => {
  excludeExpressionData.value = []
  checkExcludeBtnList.value = []
}

const tagEventBtn = (value) => {
  if (modelType.value == 'seeInfo') {
    return
  }
  expressionData.value.push({
    tm: new Date().getTime(),
    value: value
  })
}

const tagExcludeEventBtn = (value) => {
  if (modelType.value == 'seeInfo') {
    return
  }
  excludeExpressionData.value.push({
    tm: new Date().getTime(),
    value: value
  })
}

// 阶段
const addTreatStageBtn = async () => {
  let data = []
  await getEventName({ dictTypeId: 1 }).then((res) => {
    data = res.data
  })
  treatStageData.value.push({
    name: '',
    eventType: '诊断',
    event: '',
    compare: '=',
    dictData: data
  })
}

defineExpose({
  init
})
</script>
<style lang="less" scoped>
.title-item {
  width: 100%;
  height: 32px;
  background: #f7f8fa;
  color: #1d2129;
  line-height: 32px;
  font-weight: 600;
  margin: 18px 0 12px 0;
  padding-left: 16px;
}

.title-item-tip {
  color: #1d2129;
  margin-bottom: 5px;
}

.item-name {
  width: 80px;
  display: inline-block;
  text-align: right;
  margin-right: 10px;
}

.check-tags .ant-tag.ant-tag-has-color {
  color: #3491fa;
  cursor: pointer;
}
</style>
